class WebSocketService {
    constructor() {
        this.socket = null;
        this.messageHandlers = [];
        this.openHandlers = [];
        this.closeHandlers = [];
    }

    connect(url) {
        this.socket = new WebSocket(url);

        this.socket.onopen = () => {
            console.log('WebSocket连接已建立');
            this.openHandlers.forEach(handler => handler());
        };

        this.socket.onmessage = (event) => {
            const data = JSON.parse(event.data);
            this.messageHandlers.forEach(handler => handler(data));
        };

        this.socket.onclose = () => {
            console.log('WebSocket连接已关闭');
            this.closeHandlers.forEach(handler => handler());
        };

        this.socket.onerror = (error) => {
            console.error('WebSocket错误:', error);
        };
    }

    onMessage(handler) {
        this.messageHandlers.push(handler);
    }

    onOpen(handler) {
        this.openHandlers.push(handler);
    }

    onClose(handler) {
        this.closeHandlers.push(handler);
    }

    sendMessage(message) {
        if (this.socket && this.socket.readyState === WebSocket.OPEN) {
            this.socket.send(JSON.stringify(message));
        }
    }

    close() {
        if (this.socket) {
            this.socket.close();
        }
    }
}

export default new WebSocketService();
